package com.dg11185.nearshop.activity.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.client.HttpRequest.ActionListener;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.net.request.ActivableRequest;
import com.dg11185.nearshop.net.request.ActiveRequest;
import com.dg11185.nearshop.net.request.AddCardRequest;
import com.dg11185.nearshop.net.response.ActivableResponse;
import com.dg11185.nearshop.net.response.ActiveResponse;
import com.dg11185.nearshop.net.response.AddCardResponse;
import com.wlper.lib.uitls.LogUtils;
import com.wlper.lib.uitls.StringUtils;
import com.wlper.lib.uitls.ViewUtils;

/**
 * 激活界面
 * 
 * @author wanliang527
 * 
 */
public class ActivationActivity extends SubPageActivity {

    private String userPhone; // 由个人中心主界面传递过来的用户手机号，有可能为null
    private String loginName; // 由个人中心主界面传递过来的用户登录名，用于传递给绑定常惠卡界面

    private EditText phoneBox, cardNoBox, passwdBox, codeBox;// 手机号输入框、卡号输入框、密码输入框、验证码输入框
    private Button getCodeBtn, activateBtn;// 获取验证码按钮、激活按钮
    private TextView bindBtn, changePhoneHint;// 跳转绑定界面按钮、改变手机号提示

    private LinearLayout codeLayout;// 验证码视图

    private boolean isInitView;
    private boolean isDefaultPhone; // 激活卡的手机号是否是默认的

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSubPageTitle("激活常惠卡");
        setContentView(R.layout.activity_activate);
        userPhone = getIntent().getStringExtra("mobilePhone");
        loginName = getIntent().getStringExtra("loginName");
        initView();
    }

    private void findViewsId() {
        phoneBox = (EditText) findViewById(R.id.edit_phone);
        codeBox = (EditText) findViewById(R.id.edit_code);
        cardNoBox = (EditText) findViewById(R.id.edit_card_num);
        passwdBox = (EditText) findViewById(R.id.edit_passwd);
        activateBtn = (Button) findViewById(R.id.btn_activate);
        getCodeBtn = (Button) findViewById(R.id.btn_get_code);
        bindBtn = (TextView) findViewById(R.id.txt_v_bind_card);
        changePhoneHint = (TextView) findViewById(R.id.txt_v_change_phone_hint);
        codeLayout = (LinearLayout) findViewById(R.id.llayout_code);
        isInitView = true;
    }

    private void initView() {
        findViewsId();
        activateBtn.setOnClickListener(clickListener);
        getCodeBtn.setOnClickListener(clickListener);
        bindBtn.setOnClickListener(clickListener);
        // 手机号码输入监听器
        phoneBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // 判断手机输入框里的内容是否跟用户的手机号想同
                String str = phoneBox.getText().toString();
                if (!str.equals(userPhone)) {
                    // 如果不相同，就显示出验证码输入框和发送验证码按钮
                    setCodeLayoutState(true);
                    isDefaultPhone = false;
                } else {
                    // 如果相同，就隐藏验证码输入框和发送验证码按钮
                    setCodeLayoutState(false);
                    isDefaultPhone = true;
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        if (userPhone != null) {
            // 如果该用户有手机号
            // 手机号输入框失焦，卡号输入框获得焦点
            // 隐藏验证码输入框，改变提示语为“提示：您也可以使用其它......”
            phoneBox.setText(userPhone);
            cardNoBox.requestFocus();
            isDefaultPhone = true;
            setCodeLayoutState(false);
        } else {
            // 如果没有手机号
            // 手机号输入框获得焦点
            // 显示验证码输入框，改变提示语为“您已更换手机号......”
            phoneBox.requestFocus();
            isDefaultPhone = false;
            setCodeLayoutState(true);
        }
    }

    /**
     * 改变验证码输入框和获取验证码按钮的状态，同时也会改变提示语
     * 
     * @param visible
     */
    private void setCodeLayoutState(boolean visible) {
        int v = View.VISIBLE;
        int hintId = R.string.changed_phone_hint;
        // int btnStrId = R.string.activate;
        if (!visible) {
            v = View.INVISIBLE;
            hintId = R.string.change_phone_hint;
            // btnStrId = R.string.activate_and_bind;
        }
        // activateBtn.setText(btnStrId);
        changePhoneHint.setText(hintId);
        codeLayout.setVisibility(v);
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            // 获取验证码按钮，实际上是检测当前手机和卡号是否可以激活
                case R.id.btn_get_code:
                    onCheckIsActivable();
                    break;
                // 激活按钮
                case R.id.btn_activate:
                    onActivate();
                    break;
                // 去绑定按钮
                case R.id.txt_v_bind_card:
                    Intent goBind = new Intent(mActivity, AddCardActivity.class);
                    goBind.putExtra("loginName", loginName);
                    startActivity(goBind);
                    mActivity.finish();
                    break;
            }

        }

    };

    /**
     * 联网检测是否可激活
     */
    private void onCheckIsActivable() {
        String cardNo = cardNoBox.getText().toString();
        String phone = phoneBox.getText().toString();
        String pwd = passwdBox.getText().toString();
        if (checkPhoneNum(phone) && checkCardNo(cardNo) && checkCardPwd(pwd)) {
            showLoading();
            final ActivableRequest request = new ActivableRequest(cardNo, phone);
            // 如果用户没有绑定过手机号或者绑定的手机号与现在输入的手机号不一致的话，需要发送短信验证
            request.add(ActivableRequest.sendVc, "1");
            request.encryption();
            request.setActionListener(new ActionListener<ActivableResponse>() {

                @Override
                public void onSuccess(ActivableResponse result) {
                    LogUtils.logNetReturn(Constants.activable,
                            result.responseStr);
                    hideLoading();
                    onCheckIsActivableRet(result);
                }

                @Override
                public void onFailure(int resultCode) {
                    hideLoading();
                    LogUtils.logNetError("可激活检测失败--" + resultCode);
                    if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                        ViewUtils.showToast(mActivity,
                                R.string.cant_connect_network);
                    } else {
                        ViewUtils.showToast(mActivity, R.string.network_error);
                    }
                }
            });
            NetClient.httpPost(request);
        }
    }

    /**
     * 是否可激活的返回结果处理
     * 
     * @param result
     */
    private void onCheckIsActivableRet(ActivableResponse result) {
        if (result.status.equals(ActivableResponse.SUCCESS)) {
            ViewUtils.showToast(mActivity, "验证码已发送！");
            phoneBox.setEnabled(false);
            cardNoBox.setEnabled(false);
        } else if (result.status.equals(ActivableResponse.FAILE)) {
            ViewUtils.showToast(mActivity, "手机号不可用");
        } else if (result.status.equals(ActivableResponse.CARD_ACTIVED)) {
            ViewUtils.showToast(mActivity, "卡号已激活");
        } else if (result.status.equals(ActivableResponse.CARD_NOTFOUND)) {
            ViewUtils.showToast(mActivity, "卡号不存在");
        } else if (result.status.equals(ActivableResponse.REQ_UN_TIMEOUT)) {
            ViewUtils.showToast(mActivity, "5分钟内不允许重复发送验证码");
        } else {
            LogUtils.logNetError("可激活检测失败--" + result.status);
            ViewUtils.showToast(mActivity, R.string.network_error);
        }
    }

    /**
     * 联网激活常惠卡
     */
    private void onActivate() {
        String phone = phoneBox.getText().toString();
        String cardNo = cardNoBox.getText().toString();
        String passwd = passwdBox.getText().toString();
        String code = codeBox.getText().toString();
        // String checkPasswdRes = StringUtils.checkPasswdStr(passwd);
        if (!checkPhoneNum(phone) || !checkCardNo(cardNo)
                || !checkCardPwd(passwd))
            return;

        final ActiveRequest activeRequest = new ActiveRequest(cardNo, passwd,
                phone);
        if (userPhone == null || !userPhone.equals(phone)) {
            if (StringUtils.isStrNull(code)) {
                ViewUtils.showToast(mActivity, "验证码不能为空");
                return;
            }
            activeRequest.add(ActiveRequest.msgCode, code);
        }
        activeRequest.encryption();
        showLoading();
        activeRequest.setActionListener(new ActionListener<ActiveResponse>() {
            @Override
            public void onSuccess(ActiveResponse result) {
                LogUtils.logNetReturn(Constants.active, result.responseStr);
                // hideLoading();
                onActivateRet(result);
            }

            @Override
            public void onFailure(int resultCode) {
                hideLoading();
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    ViewUtils.showToast(mActivity,
                            R.string.cant_connect_network);
                } else {
                    LogUtils.logNetError("激活失败---" + resultCode);
                    ViewUtils.showToast(mActivity, R.string.network_error);
                }

            }
        });
        NetClient.httpPost(activeRequest);
    }

    /**
     * 处理激活结果
     * 
     * @param result
     */
    private void onActivateRet(ActiveResponse result) {
        if (result.status.equals(ActiveResponse.SUCCESS)) {
            // 如果用户激活该卡的手机号与用户手机号一致的话，系统会自动进行绑定
            // 否则，要再调用绑定接口进行绑定操作
            // if (isDefaultPhone) {
            // showDialog("激活并绑定成功", "点击“确定”返回个人中心").setPositiveButton("确定",
            // new View.OnClickListener() {
            // @Override
            // public void onClick(View v) {
            // setResult(RESULT_OK);
            // finish();
            // }
            // });
            // } else {
            onAddCard();
            return;
            // }

        } else if (result.status.equals(ActiveResponse.FAILE)) {
            ViewUtils.showToast(mActivity, "手机号不可用");
        } else if (result.status.equals(ActiveResponse.ILLEGAL_VC)) {
            ViewUtils.showToast(mActivity, "验证码无效");
        } else if (result.status.equals(ActiveResponse.CARD_NOTFOUND)) {
            ViewUtils.showToast(mActivity, "卡号不存在");
        } else if (result.status.equals(ActiveResponse.CARD_ILLEGALPWD)) {
            ViewUtils.showToast(mActivity, "卡密错误");
        } else if (result.status.equals(ActivableResponse.CARD_ACTIVED)) {
            // 如果卡号已激活，询问用户是否将该卡绑定到该账户下
            showDialog("激活失败", "您的常惠卡已激活，点击“确定”将卡绑定到该账户下").setPositiveButton(
                    "确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onAddCard();
                            hideDialog();
                            showLoading();
                        }
                    });

        } else {
            LogUtils.logNetError("激活失败---" + result.status);
            ViewUtils.showToast(mActivity, R.string.network_error);
        }
        hideLoading();
    }

    private void onAddCard() {
        String cardNo = cardNoBox.getText().toString();
        String passwd = passwdBox.getText().toString();
        AddCardRequest req = new AddCardRequest(loginName, cardNo, passwd);
        req.setActionListener(new ActionListener<AddCardResponse>() {
            @Override
            public void onSuccess(AddCardResponse result) {
                LogUtils.logNetReturn(Constants.add, result.responseStr);
                hideLoading();
                onAddCardRet(result);
            }

            @Override
            public void onFailure(int resultCode) {
                hideLoading();
                LogUtils.logNetError("绑定失败---" + resultCode);
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    ViewUtils.showToast(mActivity,
                            R.string.cant_connect_network);
                } else {
                    ViewUtils.showToast(mActivity, R.string.network_error);
                }
            }
        });
        NetClient.httpPost(req);
    }

    private void onAddCardRet(AddCardResponse result) {
        String status = result.status;
        if (status.equals(AddCardResponse.SUCCESS)) {
            showDialog("激活并绑定成功", "点击“确定”返回个人中心").setPositiveButton("确定",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
        } else if (status.equals(AddCardResponse.CARD_NOTFOUND)) {
            ViewUtils.showToast(mActivity, "卡号不存在");
        } else if (status.equals(AddCardResponse.CARD_ILLEGALPWD)) {
            ViewUtils.showToast(mActivity, "卡密错误");
        } else if (status.equals(AddCardResponse.CARD_MAPPING)) {
            ViewUtils.showToast(mActivity, "该卡已被绑定");
        } else if (status.equals(AddCardResponse.CARD_INVALID)) {
            ViewUtils.showToast(mActivity, "该卡已锁定");
        } else {
            LogUtils.logNetError("绑定失败---" + status);
            ViewUtils.showToast(mActivity, R.string.network_error);
        }
    }

    /**
     * 检查手机号是否合法
     * 
     * @param num
     * @return
     */
    private boolean checkPhoneNum(String num) {
        if (StringUtils.isStrNull(num)) {
            ViewUtils.showToast(mActivity, "手机号不能为空！");
            return false;
        }
        if (!StringUtils.isLengthValid(11, 11, num)) {
            ViewUtils.showToast(mActivity, "手机号长度必须为11位！");
            return false;
        }
        if (!StringUtils.isMobileNumValid(num)) {
            ViewUtils.showToast(mActivity, "非法手机号，请重新输入！");
            return false;
        }
        return true;
    }

    /**
     * 检查常惠卡卡号是否合法
     * 
     * @param cardNo
     * @return
     */
    private boolean checkCardNo(String cardNo) {
        if (StringUtils.isStrNull(cardNo)) {
            ViewUtils.showToast(mActivity, "卡号不能为空！");
            return false;
        }
        return true;
    }

    /**
     * 检查密码是否合法，并作出处理
     * 
     * @param pwd
     * @return
     */
    private boolean checkCardPwd(String pwd) {
        if (StringUtils.isStrNull(pwd)) {
            ViewUtils.showToast(mActivity, "常惠卡密码不能为空！");
            return false;
        }
        String str = StringUtils.checkPasswdStr(pwd);
        if (!str.equals("OK")) {
            ViewUtils.showToast(mActivity, str);
            return false;
        } else {
            return true;
        }
    }

}
